package com.amose.handler;

import com.amose.config.Configuration;
import com.amose.config.MapperStatement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.naming.NamingException;
import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author yangpeng
 * @time 2020/2/22
 * @since 1.0.0
 * 解析sqlMapper
 */
public class SqlMapperHandler {

    private Configuration configuration;

    public SqlMapperHandler(Configuration configuration){
        this.configuration = configuration;
    }

    public void parse(InputStream in) throws DocumentException {
        Document document = new SAXReader().read(in);
        Element rootElement = document.getRootElement();
        Element mappers = rootElement.element("mappers");
        //文件区分标识
        String nameSpaceId = mappers.attributeValue("nameSpace");
        List<Element> list = mappers.elements("select");
        List<Element> updateList = mappers.elements("update");
        List<Element> addList = mappers.elements("insert");
        List<Element> deleteList = mappers.elements("delete");
        analysisSqlTypeElement(nameSpaceId, list);
        analysisSqlTypeElement(nameSpaceId, updateList);
        analysisSqlTypeElement(nameSpaceId, addList);
        analysisSqlTypeElement(nameSpaceId, deleteList);

    }

    private void analysisSqlTypeElement(String nameSpaceId, List<Element> elements) {
        for(Element element : elements) {
            MapperStatement mapperStatement = new MapperStatement();
            // sql 区分标识
            String id = element.attributeValue("id");
            String paramType = element.attributeValue("paramType");
            String resultType = element.attributeValue("resultType");
            String sqlText = element.getTextTrim();
            mapperStatement.setId(id);
            mapperStatement.setParamType(paramType);
            mapperStatement.setResultType(resultType);
            mapperStatement.setSqlText(sqlText);
            mapperStatement.setSqlType(element.getName());
            configuration.getSqlMapperStatement().put(nameSpaceId + "." + id, mapperStatement);
        }
    }
}
